package com.yanqu.road.server.manager.unionwar;

import com.yanqu.road.entity.activity.unionwar.UnionQunyingTimeInfo;
import com.yanqu.road.entity.activity.unionwar.cross.CrossUnionWarDetail;
import com.yanqu.road.entity.activity.unionwar.cross.CrossUnionWarSimple;
import com.yanqu.road.entity.activity.unionwar.cross.CrossUnionWarState;
import com.yanqu.road.entity.rank.UnionActivityRank;
import com.yanqu.road.entity.unionwar.CrossUnionGuessData;
import com.yanqu.road.entity.unionwar.GuessUnionInfo;
import com.yanqu.road.logic.bussiness.activity.UnionWarActivityBusiness;
import com.yanqu.road.logic.cross.CrossUnionWarRankListModel;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.player.PlayerProto;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionWarGuessDataListModel {
    private int activityId;
    private int phase;
    private boolean isChange = false;
    private boolean isNeedSync = false;
    //userId
    private Map<Long, CrossUnionGuessData> unionGuessMap; //竞猜数据
    //unionUid
    private Map<String, GuessUnionInfo> guessUnionInfoMap;  //竞猜商会信息

    //分组id
    private int groupId;

    public CrossUnionWarGuessDataListModel(int activityId, int phase, int groupId) {
        this.activityId = activityId;
        this.phase = phase;
        this.unionGuessMap = new ConcurrentHashMap<>();
        this.guessUnionInfoMap = new ConcurrentHashMap<>();
        this.groupId = groupId;
    }

    public void save() {
        for (Map.Entry<Long, CrossUnionGuessData> dataEntry : unionGuessMap.entrySet()) {
            CrossUnionGuessData data = dataEntry.getValue();
            if(data.getGroupId() != groupId){
                data.setGroupId(groupId);
            }
            if (data.isInsertOption()) {
                UnionWarActivityBusiness.addCrossGuessData(data);
            } else if (data.isUpdateOption()) {
                UnionWarActivityBusiness.updateCrossGuessData(data);
            }
        }
    }

    /**
     * 同步玩家竞猜数据
     * @param serverId      服务器id
     * @param userId        玩家id
     * @param unionUidList  竞猜列表
     * @param playerBaseInfo
     */
    public void changeUnionGuess(long serverId, long userId, List<String> unionUidList, PlayerProto.PlayerBaseTempMsg playerBaseInfo) {
        synchronized (unionGuessMap) {
            if (!unionGuessMap.containsKey(userId)) {
                CrossUnionGuessData crossUnionGuessData = new CrossUnionGuessData();
                crossUnionGuessData.setActivityId(activityId);
                crossUnionGuessData.setStage(phase);
                crossUnionGuessData.setServerId(serverId);
                crossUnionGuessData.setUserId(userId);
                crossUnionGuessData.setInsertOption();
                crossUnionGuessData.setGroupId(getGroupId());
                unionGuessMap.put(userId, crossUnionGuessData);
            }
            CrossUnionGuessData crossUnionGuessData = unionGuessMap.get(userId);
            crossUnionGuessData.setUnionUid(unionUidList);
            crossUnionGuessData.setUserBaseInfo(PlayerBasePb.parseBaseUserInfo(playerBaseInfo));
            crossUnionGuessData.setSyncTime(System.currentTimeMillis());
            isChange = true;
            syncPopularity();
        }
    }

    /**
     * 同步竞猜热度
     */
    public void syncPopularity() {
        if (isChange) {
            synchronized (guessUnionInfoMap) {
                initPopularity();
                for (Map.Entry<Long, CrossUnionGuessData> dataEntry : unionGuessMap.entrySet()) {
                    CrossUnionGuessData guessData = dataEntry.getValue();
                    for (String unionUid : guessData.getUnionUid()) {
                        if (guessUnionInfoMap.containsKey(unionUid)) {
                            guessUnionInfoMap.get(unionUid).addGuessPopularity();
                        }
                    }
                }
            }
            isChange = false;
            isNeedSync = true;
        }
    }

    /**
     * 初始化竞猜数据
     */
    public boolean initGuessUnionInfoMap() {
        boolean initSuccess = false;
        synchronized (guessUnionInfoMap) {
            if (phase == 1) {   //积分赛
                List<CrossUnionWarSimple> crossUnionWarSimpleList = CrossUnionWarMgr.getCrossUnionWarSimpleList(activityId);
                crossUnionWarSimpleList = CrossUnionWarMgr.filterUnionData(activityId, getGroupId(), crossUnionWarSimpleList);
                for (CrossUnionWarSimple crossUnionWarSimple : crossUnionWarSimpleList) {
                    if (!guessUnionInfoMap.containsKey(crossUnionWarSimple.getUnionUid())) {
                        guessUnionInfoMap.put(crossUnionWarSimple.getUnionUid(), initGuessUnionInfo(crossUnionWarSimple));
                    }
                }
            } else if (phase == 2) {    //决赛
                //检测积分赛最后一场是否已开战
                CrossUnionWarState crossUnionWarState = CrossUnionWarMgr.getCrossUnionWarState(activityId, 1, CrossUnionWarActivityMgr.getAllSession(activityId, 1), getGroupId());
                if(crossUnionWarState.getState() != 2){
                    return false;
                }
                //检测积分赛最后一场是否都已积分
                List<CrossUnionWarDetail> lastList = CrossUnionWarMgr.getCrossUnionWarDetailList(activityId, 1, CrossUnionWarActivityMgr.getAllSession(activityId, 1), getGroupId());
                if(lastList == null){
                    CrossUnionWarMgr.getLogger().info("======= groupId {} not data", this.getGroupId());
                    return false;
                }
                for(CrossUnionWarDetail detail : lastList) {
                    if (!detail.isAddScore()) {
                        return false;
                    }
                }
                CrossUnionWarRankListModel crossUnionWarRankListModel = CrossUnionWarRankMgr.getCrossUnionWarRankListModel(activityId, 2, getGroupId());
                if (crossUnionWarRankListModel == null) {
                    return false;
                }
                LinkedList<UnionActivityRank> rankList = crossUnionWarRankListModel.getRankList();
                int n = 32; //决赛取前n名入围
                UnionQunyingTimeInfo qunyingTimeInfo = CrossUnionWarActivityMgr.getUnionQunyingTimeInfo(activityId, 2, 0);
                try{
                    n = Integer.valueOf(qunyingTimeInfo.getParam());
                }catch (Exception e){
                    CrossUnionWarMgr.getLogger().error(e.getMessage(), e);
                }
                for (int i = 0; i < n; i++) {
                    UnionActivityRank unionActivityRank = rankList.get(i);
                    CrossUnionWarSimple crossUnionWarSimple = CrossUnionWarMgr.getCrossUnionWarSimple(activityId, unionActivityRank.getUnionUid());
                    if (crossUnionWarSimple != null) {
                        if (!guessUnionInfoMap.containsKey(crossUnionWarSimple.getUnionUid())) {
                            guessUnionInfoMap.put(crossUnionWarSimple.getUnionUid(), initGuessUnionInfo(crossUnionWarSimple));
                            initSuccess = true;
                        }
                    }
                }
            }
            isChange = true;
            syncPopularity();
        }
        return initSuccess;
    }

    private GuessUnionInfo initGuessUnionInfo(CrossUnionWarSimple crossUnionWarSimple) {
        GuessUnionInfo guessUnionInfo = new GuessUnionInfo();
        guessUnionInfo.setActivityId(activityId);
        guessUnionInfo.setPhase(phase);
        guessUnionInfo.setUnionUid(crossUnionWarSimple.getUnionUid());
        guessUnionInfo.setUnionBaseInfo(crossUnionWarSimple.getUnionBaseInfo());
        guessUnionInfo.setGuessPopularity(0);
        guessUnionInfo.setGroupId(crossUnionWarSimple.getGroupId());
        guessUnionInfo.setLastUpdateTime(System.currentTimeMillis());
        return guessUnionInfo;
    }

    /**
     * 初始化热度
     */
    public void initPopularity() {
        synchronized (guessUnionInfoMap) {
            for (GuessUnionInfo unionInfo : guessUnionInfoMap.values()) {
                unionInfo.setGuessPopularity(0);
            }
        }
    }

    public int getActivityId() {
        return activityId;
    }

    public void setActivityId(int activityId) {
        this.activityId = activityId;
    }

    public int getPhase() {
        return phase;
    }

    public void setPhase(int phase) {
        this.phase = phase;
    }

    public boolean isChange() {
        return isChange;
    }

    public void setChange(boolean change) {
        isChange = change;
    }

    public Map<Long, CrossUnionGuessData> getUnionGuessMap() {
        return unionGuessMap;
    }

    public void setUnionGuessMap(Map<Long, CrossUnionGuessData> unionGuessMap) {
        this.unionGuessMap = unionGuessMap;
    }

    public boolean isNeedSync() {
        return isNeedSync;
    }

    public void setNeedSync(boolean needSync) {
        isNeedSync = needSync;
    }

    public Map<String, GuessUnionInfo> getGuessUnionInfoMap() {
        return guessUnionInfoMap;
    }

    public int getGroupId() {
        return groupId;
    }

    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }
}

